<?php

function village_activity_add_page($id) {
    return drupal_get_form('village_activity_edit_form',$id);
}

function village_activity_edit_page($id) {
    return drupal_get_form('village_activity_edit_form', $id);
}

function village_activity_edit_form($form, &$form_state) {
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    if (!empty($id)) {
        $record = nonghua_data_load('village_activity', 'village_activity_id', $id);
        if (empty($record)) {
            drupal_set_message(t('村落活动不存在！'), 'status', FALSE);
            return $form;
        }
    }
    // 判断用户角色
    if(!nonghua_user_access('village_activity', 'view', $id, !empty($record) ? $record->author_uid:0, 0) ){
        drupal_set_message(t('您没有权限查看本条数据！'), 'status', FALSE);
        return $form;
    }
    $form['address_fuzzy'] = _insert_address_autocomplete($form, $form_state,isset($record) && !empty($record)?$record->addr_id:'');
    if (!empty($_GET['addr_id'])) {
        $form_state['addr_id'] = $_GET['addr_id'];
        $form['#addr_id'] = $_GET['addr_id'];
        $form['address'] = _insert_address_selection_form($form, $form_state,'address', 5, TRUE, $form_state['addr_id'] ,'');
    }else{
        $form['address'] = _insert_address_selection_form($form, $form_state,'address', 5, TRUE,  !empty($record) ? $record->addr_id:'','');
    }
//    $form['distributor'] = get_all_distributors(!empty($record) ? $record->distributor_id : '');
    $form['distributor_name'] = _insert_distributor_select_info($form,$form_state,$record->distributor_id);
    $form['title'] = array(
        '#type' => 'textfield',
        '#title' => '活动标题',
        '#default_value' => !empty($record) ? $record->title : '',
        '#size' => 32,
        '#maxlength' => 20,
        '#required' => TRUE,
    );
    $form['body'] = array(
        '#type' => 'textarea',
        '#title' => '活动内容',
        '#default_value' => !empty($record) ? $record->body : '',
        '#required' => TRUE,
        '#maxlength' => 500,
        '#attributes'=>array('placeholder'=>'最多输入500字。')
    );
    $form['attendee'] = array(
        '#type' => 'textarea',
        '#title' => '参加人员',
        '#default_value' => !empty($record) ? $record->attendee : '',
        '#size' => 32,
        '#maxlength' => 50,
        '#attributes'=>array('placeholder'=>'最多输入50字。')
    );
    $form['date'] = array(
        '#type' => 'metercomm_date',
        '#title' => '活动日期',
        '#default_value' =>_date_db_2_form(!empty($record) ? $record->date : ''),
        '#required' => TRUE,
    );
    $form['comments'] = array(
        '#type' => 'textarea',
        '#title' => '其他',
        '#default_value' => !empty($record) ? $record->comments : '',
        '#maxlength' => 50,
        '#attributes'=>array('placeholder'=>'最多输入50字。')
    );
    insert_special_activities($form,$form_state,isset($record) && !empty($record)?$record:'');
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => arg(2)!='add' ? '修改' : '添加',
        '#access' => nonghua_user_access('village_activity', 'edit', $id, !empty($record) ? $record->author_uid:0, 0) ,
    );
    return $form;
}

function village_activity_edit_form_validate($form, &$form_state) {
    if(empty($form_state['values']['distributor_name'])){
        form_set_error('distributor', '必须填写 经销商');
    }

    if(!empty($form_state['values']['address_fuzzy'])){
        $addr_object = addr_load_by_full_name($form_state['values']['address_fuzzy']);
        if(empty($addr_object)){
            form_set_error('address_fuzzy', '请根据提示输入正确（完整）的地址信息');
            $validate = false;
        }elseif($addr_object->geo_level !== "5"){
            form_set_error('address_fuzzy', '请根据提示输入村落地址信息');
        }

    }else if(empty($form_state['values']['village'])){
        form_set_error('village', '必须填写 地址,输入地址或点选省市县乡镇村地址，两种方式任选其一');
        $validate = false;
    }
    if(!empty($form_state['values']['distributor_name'])){
        $distributor_id = get_id_from_string_field('distributor','distributor_id','distributor_name',$form_state['values']['distributor_name'],false);
        if(empty($distributor_id)){
            form_set_error('distributor_name', "经销商信息不存在！");
        }
    }
//    if(empty($form_state['values']['village_activity'])){
//        form_set_error('village_activity', '必须填写 村落活动');
//    }else if(!isset($form_state['build_info']['args'][0])){
//        $record = db_select('village_activity', 'u')
//            ->condition('u.addr_id', $form_state['values']['village_activity'])
//            ->fields('u')
//            ->execute()->fetchAssoc();
//        if (!empty($record)) {
//            form_set_error('village_activity', "该村落活动信息已存在！");
//        }
//    }

}

function village_activity_edit_form_submit($form, &$form_state) {
    global $user;
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    $address =  _get_address_id_from_autocomplete_select($form_state);

    if (arg(2) =='add') { //add new village_activity
        $nid = db_insert('village_activity') // Table name no longer needs {}
                ->fields(array(
                    'addr_id' => $address,
                    'distributor_id' =>get_id_from_string_field('distributor','distributor_id','distributor_name',$form_state['values']['distributor_name'],false),
                    'title' => $form_state['values']['title'],
                    'body' => $form_state['values']['body'],
                    'attendee' => $form_state['values']['attendee'],
                    'date' => _date_form_2_db($form_state['values']['date']),
                    'comments' => $form_state['values']['comments'],
                    'special_activities_id'=>get_id_from_string_field('special_activities','special_activities_id','title',$form_state['values']['special_activities']),
                    'author_uid' => $user->uid,
                    'timestamp' => time(),))
                ->execute();
        if ($nid > 0) {
            drupal_set_message(t('添加成功！'), 'status', FALSE);
            if(!empty($_GET['addr_id'])){
                drupal_goto('village/activity/list',array('query' => array('addr_id' => $_GET['addr_id'])));
            }
             drupal_goto('village/activity/add/'.$nid);
        }

    } else {
        $nid = db_update('village_activity')// edit exsting store. todo: update only modified fields
        ->fields(array(
            'addr_id' => $address,
            'distributor_id' => get_id_from_string_field('distributor','distributor_id','distributor_name',$form_state['values']['distributor_name'],false),
            'title' => $form_state['values']['title'],
            'body' => $form_state['values']['body'],
            'attendee' => $form_state['values']['attendee'],
            'date' => _date_form_2_db($form_state['values']['date']),
            'comments' => $form_state['values']['comments'],
            'special_activities_id'=>get_id_from_string_field('special_activities','special_activities_id','title',$form_state['values']['special_activities']),
            'author_uid' => $user->uid,
            'timestamp' => time(),))
            ->condition('village_activity_id', $id, '=')
            ->execute();
        if ($nid > 0) {
            drupal_set_message(t('修改成功！'), 'status', FALSE);
        }
        if(!empty($_GET['addr_id'])){
            drupal_goto('village/activity/list',array('query' => array('addr_id' => $_GET['addr_id'])));
        }

    }
}


